﻿using System;
using System.Xml;
using System.Collections.ObjectModel;

namespace Builderator.Core.Components
{
    public class ServerList : ObservableCollection<Server>
    {
        public ServerList()
            : base()
        {

        }

        public ServerList(string settings)
        {
            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(settings);

            XmlElement rootElement = xmlDoc.DocumentElement;

            foreach (XmlElement child in rootElement.ChildNodes)
            {
                this.Add(new Server(child.OuterXml));
            }
        }

        public void Update(string server, string domain)
        {
            foreach (Server item in this)
            {
                if (server == item.Name)
                {
                    item.Name = domain;

                    break;
                }
            }
        }

        public bool Exists(Server server)
        {
            foreach (Server item in this)
            {
                return (server.Name == item.Name) ? true : false;
            }

            return false;
        }

        public override string ToString()
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlDocumentFragment childElement;
            XmlElement rootElement = xmlDoc.CreateElement("ServerList");

            foreach (Server server in this)
            {
                childElement = xmlDoc.CreateDocumentFragment();

                childElement.InnerXml = server.ToString();

                rootElement.AppendChild(childElement);
            }

            xmlDoc.AppendChild(rootElement);

            return xmlDoc.InnerXml;
        }
    }
}
